package com.brayan.webapp.service.general.i18n;

import javax.ejb.Stateless;
import javax.inject.Inject;

import org.apache.log4j.Logger;

import com.brayan.webapp.model.general.i18n.Locale;
import com.brayan.webapp.model.general.i18n.Translation;
import com.brayan.webapp.repository.general.country.CountryRepository;
import com.brayan.webapp.repository.general.i18n.LanguageRepository;
import com.brayan.webapp.repository.general.i18n.LocaleRepository;
import com.brayan.webapp.repository.general.i18n.TextRepository;
import com.brayan.webapp.repository.general.i18n.TranslationRepository;

@Stateless
public class TranslationBean {

	private static Logger LOGGER = Logger.getLogger(TranslationBean.class);

	@Inject
	TextRepository textRepo;
	@Inject
	TranslationRepository transRepo;
	@Inject
	LanguageRepository languageRepo;
	@Inject
	CountryRepository countryRepo;
	@Inject
	LocaleRepository localeRepo;
	

	public void saveTranslation(Long textUnitId, String localeCode, String translationText) {
		Translation trans = null;

		String languageCode = localeCode.substring(0, 2);
		String countryCode = null;
		if (localeCode.length() == 5)
			countryCode = localeCode.substring(3, 5);

		if (countryCode != null && countryCode.length() == 2)
			trans = transRepo.getTranslationByTextIdAndLocaleCode(textUnitId, languageCode, countryCode);
		else
			trans = transRepo.getTranslationByTextIdAndLanguageCode(textUnitId, languageCode);		
		
		// At this point it could be that the translation does not yet exists.		
		Locale locale = new Locale();		
		
		// Create a new one if not found.
		if (trans == null) {
			LOGGER.info("Creating new translation (" + translationText + ") for text token's (id: " + textUnitId + ").");
			trans = new Translation();	
			// Retrieve an existing Locale. We do not create one, if locale is null!!!
			if (countryCode != null && countryCode.length() == 2)
				locale = localeRepo.getLocaleByLanguageAndCountry(languageCode, countryCode);
			else
				locale = localeRepo.getLocaleByLanguage(languageCode);			
		} else {
			LOGGER.info("Changing text token's (id: " + textUnitId + ") translation from " + trans.getTranslation()
					+ " to " + translationText + ".");			
		}

		// Now insert or update the values of the translation.
		trans.setTranslation(translationText);		
		trans.setTextUnit(textRepo.getText(textUnitId));		
		if(trans.getLocale() == null){
			trans.setLocale(locale);
		}			

		transRepo.saveTranslation(trans);
	}

}
